package com.hxx.utils;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class LoginFilter implements Ordered, GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange,
                                             GatewayFilterChain chain) {
        //获取请求路径
        String path = exchange.getRequest().getURI().getPath();
        //放行的路径
        if (path.contains("/admin")
                || path.contains("/train-member/sendCode")
                || path.contains("/train-member/login")){
           return chain.filter(exchange);
        }
        //获取令牌token
        String token = exchange.getRequest().getHeaders().getFirst("token");
        //无令牌
        if (token==null || token.isEmpty()){
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
        //验证令牌
        if (JwtUtils.verify(token)) {
            return chain.filter(exchange);
        }else {
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
    }

    @Override
    public int getOrder() {
        //值越小执行的优先级越高
        return 0;
    }
}

































